﻿using EMoney.IStock.Client.Core;
using EMoney.IStock.Client.Framework;
using EMoney.IStock.Client.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThinkDev.Logging;

namespace EMoney.IStock.Client.Business
{
    public class TokenBll
    {
        private static int test_userid = ConfigHelper.TestUserID;
        private const string USERIDNAME_COOKIE = "EMoney.IStock.Client.Business.TokenBll.UserIDName";
        private const string USERIDKEY_COOKID = "EMoney.IStock.Client.Business.TokenBll.UserIDKey";

        /// <summary>
        /// 获取Cookie值验证是否有权限
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        public static bool CheckRightsByCookie(FuncRights func)
        {
            if (ConfigHelper.IsOnline == "0")   //测试环境不验证
            {
                return true;
            }

            string userid = CookieHelper.GetCookie(USERIDNAME_COOKIE, USERIDKEY_COOKID);

            if (string.IsNullOrEmpty(userid))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 清除UserID缓存
        /// </summary>
        public static void RemoveUserIDCookie()
        {
            CookieHelper.RemoveCookie(USERIDNAME_COOKIE);
        }

        /// <summary>
        /// 通过用户编号获取QQ号码
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static string GetQQByUserID(int userid)
        {
            return CacheManager.DefaultCache.Get<string>(string.Concat(QQConstDefine.USERQQ_CACHED_KEY, ".", userid));
        }

        /// <summary>
        /// 从cookie获取用户编号
        /// </summary>
        /// <returns></returns>
        public static int GetUserIDByCookie()
        {
            if (test_userid != 0)
            {
                return test_userid;
            }
            int userid = 0;
            string strUserID = CookieHelper.GetCookie(USERIDNAME_COOKIE, USERIDKEY_COOKID);
            
            if (!string.IsNullOrEmpty(strUserID))
            {
                int.TryParse(strUserID, out userid);
            }
            
            return userid;
        }

        /// <summary>
        /// 通过Web接口解析临时token获取userid
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static int GetUserIDByTokenWithWS(string token)
        {
            int userid = 0;

            try
            {
                string data = string.Format("productid={1}&token={0}&version={2}&appid={3}", token, "100", 1, "100");

                string url = string.Format(ConfigHelper.SsoService + "?{0}&encrypt={1}", data, GetEncryptKey(ConfigHelper.SsoService + "?" + data));

                NetHelper net = new NetHelper();

                string result = net.GetClientBySocket(url);

                if (!string.IsNullOrEmpty(result))
                {
                    UserToken userToken = JsonHelper.ToObject<UserToken>(result);

                    if (userToken != null && userToken.resultcode == "0")
                    {
                        userid = int.Parse(userToken.userid);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), string.Concat("通过Web接口解析临时token获取userid失败.", token));
            }

            return userid;
        }

        /// <summary>
        /// 根据Token获取用户编号
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static int GetUserIDByToken(string token)
        {
            if (test_userid != 0)
            {
                return test_userid;
            }
            int userid = 0;
            string strUserID = ClientTokenHelper.GetUserIdByToken(token);

            if (!string.IsNullOrEmpty(strUserID))
            {
                if (int.TryParse(strUserID, out userid))
                {
                    CookieHelper.SetCookie(USERIDNAME_COOKIE, USERIDKEY_COOKID, strUserID, 4);
                }
            }

            return userid;
        }

        /// <summary>
        /// 验证传入的token是否存在指定的权限
        /// </summary>
        /// <param name="token"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static bool CheckRightsByToken(string token,FuncRights func)
        {
            if (ConfigHelper.IsOnline == "0")   //测试环境不验证
            {
                return true;
            }

            int userid = GetUserIDByToken(token);
            
            if (userid >= 0)
            {
                if (ClientTokenHelper.CheckUserRight(userid.ToString(), func.GetHashCode().ToString()))
                {
                    return true;
                }
            }

            return false;
        }

        private static string GetEncryptKey(string sUrl)
        {
            Uri uri;
            if (!Uri.TryCreate(sUrl, UriKind.RelativeOrAbsolute, out uri))
            {
                return sUrl;
            }

            List<string> list = new List<string>();
            string queryStr = uri.Query;
            if (queryStr.IndexOf("?") == 0)
            {
                queryStr = queryStr.Substring(1);
            }
            string[] querys = queryStr.Split('&');
            foreach (string q in querys)
            {
                list.Add(q);
            }
            list.Sort();
            list.Sort();
            StringBuilder sBuilder = new StringBuilder();
            foreach (string q in list)
            {
                sBuilder.Append(q);
            }
            string toEncrypt = sBuilder.ToString() + "12345678901234567890";
            string md5New = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(toEncrypt, "md5");
            return md5New;
        }
    }

    /// <summary>
    /// 用户信息
    /// </summary>
    public class UserToken
    {
        public string resultcode { get; set; }
        public string resultmsg { get; set; }
        public string token { get; set; }
        public string userid { get; set; }
    }
}
